﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace RadioPlayer
{
	public class RadioHelper
	{
		 private RadioList _list = new RadioList();

		 public RadioHelper()
		 {
			//désérialization XML
			FileInfo xmlFile = new FileInfo("Radios.xml");
			if (xmlFile.Exists)
			{
				XmlSerializer xs = new XmlSerializer(typeof(RadioList));
				using (StreamReader rd = new StreamReader("Radios.xml"))
				{
					_list = (RadioList)xs.Deserialize(rd);
				}
			 }
		 }

		 public void Serialize()
		 {
			 //sérialization XML
			 XmlSerializer xs = new XmlSerializer(typeof(RadioList));
			 using (StreamWriter wr = new StreamWriter("Radios.xml"))
			 {
				 xs.Serialize(wr, _list);
				 wr.Close();
			 }
		 }

	#region accessor
		 public List<RadioObject> Liste
		 {
			 get { return _list.Liste; }
		 }

		 public bool AddRadio(RadioObject radio)
		 {
			 return _list.AddRadio(radio);
		 }

		 public bool RemoveRadio(RadioObject radio)
		 {
			return _list.RemoveRadio(radio);
		 }

		 public int Count
		 {
			get {	return _list.Count;	}
		 }
	#endregion
	}

	public class RadioObject
	{
		private string _radioName = "";
		private string _streamUrl = "";

		public string RadioName
		{
			get { return _radioName; }
			set { _radioName = value; }
		}

		public string StreamUrl
		{
			get { return _streamUrl; }
			set { _streamUrl = value; }
		}

        public override string ToString()
        {
            return _radioName;
        }

		private static RadioObject Find(List<RadioObject> list, RadioObject obj)
        {
            return list.Find(new Predicate<RadioObject>(delegate(RadioObject t) { return t.Equals(obj); }));
        }
	}

	public class RadioList
	{
		private List<RadioObject> _list = new List<RadioObject>();

		public List<RadioObject> Liste
		{
			get {	return _list;	}
			set {	_list = value;	}
		}
		
		public bool AddRadio(RadioObject radio)
		{
			RadioObject foundInList = _list.Find(x => ((x.RadioName == radio.RadioName) && (x.StreamUrl == radio.StreamUrl)));
			bool result = (foundInList != null);

			if (!result)
				_list.Add(radio);

			return (!result);
		}

		public bool RemoveRadio(RadioObject radio)
		{
			RadioObject foundInList = _list.Find(x => ((x.RadioName == radio.RadioName) && (x.StreamUrl == radio.StreamUrl)));
			bool result = (foundInList != null);
			if (result)
				_list.Remove(foundInList);

			return result;
		}

		public int Count
		{
			get { return _list.Count; }
		}
	}
}
